import React, { useState, useEffect, useContext } from 'react';
import {
  Table,
  Card,
  PaginationProps,
  Button,
  Space,
  Input,
  Form,
  Grid,
  Message,
  Select,
  Badge,
  Popconfirm,
  Modal,
  Radio,
} from '@arco-design/web-react';
import { GlobalContext } from '@/context';
import {
  IconSearch,
  IconRefresh,
  IconThunderbolt,
} from '@arco-design/web-react/icon';
import styles from './style/index.module.less';
import './mock';
import { getCommentList, delComment, updateCommentStatus } from '@/api/comment';
import dayjs from 'dayjs';

const auditStatusOptions = [
  {
    value: 0,
    label: '全部',
  },
  {
    value: 1,
    label: '通过',
  },
  {
    value: 2,
    label: '驳回',
  },
  {
    value: 3,
    label: '未审核',
  },
];
function Comment() {
  const { Row, Col } = Grid;
  const { useForm } = Form;
  const [form] = useForm();
  const [formMoal] = useForm();
  const { lang } = useContext(GlobalContext);
  const colSpan = lang === 'zh-CN' ? 8 : 12;

  // 表头
  const columns: any = [
    {
      title: '文章标题',
      dataIndex: 'articleTitle',
      fixed: 'left',
      width: 160,
    },
    {
      title: '昵称',
      dataIndex: 'nickName',
    },
    {
      title: '当前回复内容',
      dataIndex: 'currentReplayContent',
    },
    {
      title: '目标回复ID',
      dataIndex: 'targetReplayId',
    },

    {
      title: '目标回复内容',
      dataIndex: 'targetReplayContent',
    },

    {
      title: '审核状态',
      dataIndex: 'auditStatus',
      render: (text) => {
        const current = auditStatusOptions.filter(
          (item) => item.value === +text
        );
        const obj = current[0];
        const enums = {
          1: 'success',
          2: 'error',
          3: 'warning',
        };
        return <Badge status={enums[obj.value]} text={obj.label} />;
      },
    },
    {
      title: '评论时间',
      dataIndex: 'commentTime',
      render: (text) => {
        return dayjs(text * 1000).format('YYYY-MM-DD HH:mm:ss');
      },
    },
    {
      title: '审核时间',
      dataIndex: 'auditTime',
      render: (text) => {
        return dayjs(text * 1000).format('YYYY-MM-DD HH:mm:ss');
      },
    },

    {
      title: '操作',
      dataIndex: 'operations',
      fixed: 'right',
      width: 200,
      render: (_, record) => (
        <div className={styles.operations}>
          <Popconfirm
            title="Are you sure you want to delete?"
            onOk={() => onDelete(record)}
          >
            <Button type="text" status="danger" size="small">
              删除
            </Button>
          </Popconfirm>

          <Button
            onClick={() => handleAudit(record)}
            type="text"
            status="success"
            size="small"
          >
            审核
          </Button>
        </div>
      ),
    },
  ];

  const [data, setData] = useState([]);
  const [pagination, setPatination] = useState<PaginationProps>({
    sizeCanChange: true,
    showTotal: true,
    pageSize: 10,
    current: 1,
    pageSizeChangeResetCurrent: true,
  });
  const [loading, setLoading] = useState(true);
  const [formParams, setFormParams] = useState({});
  const [visible, setVisible] = useState(false);
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [id, setId] = useState('');

  useEffect(() => {
    fetchData();
  }, [pagination.current, pagination.pageSize, JSON.stringify(formParams)]);

  // 获取表格数据
  async function fetchData() {
    const { current, pageSize } = pagination;
    setLoading(true);
    const params = {
      page: current,
      pageSize,
      ...formParams,
    };
    try {
      const res: any = await getCommentList(params);
      if (res.code === 200) {
        setData(res.data.list);
        setPatination({
          ...pagination,
          current,
          pageSize,
          total: res.data.total,
        });
        setLoading(false);
      } else {
      }
    } catch (error) {
      console.error(error);
    }
  }

  // 分页
  function onChangeTable(pagination) {
    setPatination(pagination);
  }

  // 查询
  function handleSearch() {
    setFormParams(form.getFields());
  }

  // 重置
  const handleReset = () => {
    form.resetFields();
  };

  // 删除
  const onDelete = async (row) => {
    console.log(row);
    setLoading(true);
    try {
      const res: any = await delComment(row._id);
      if (res.code === 200) {
        Message.success(res.msg);
        fetchData();
      } else {
        Message.error(res.msg);
        setLoading(false);
      }
    } catch (error) {
      console.error(error);
      setLoading(false);
    }
  };

  // 选择状态
  const onSelectSearch = () => {
    setFormParams(form.getFields());
  };

  // 审核
  const handleAudit = (record) => {
    setVisible(true);
    setId(record._id);
  };

  // 取消审核
  const onCancel = () => {
    setVisible(false);
    formMoal.resetFields();
    setId('');
    setConfirmLoading(false);
  };

  // 提交审核
  const onOk = async () => {
    await formMoal.validate();
    setConfirmLoading(true);
    const values = await formMoal.getFields();
    console.log(values);
    const postData = {
      id,
      ...values,
    };
    console.log('postData', postData);

    const res: any = await updateCommentStatus(postData);
    if (res.code === 200) {
      Message.success(res.msg);
      fetchData();
      onCancel();
    } else {
      Message.error('审核失败，请重试！');
      setConfirmLoading(false);
    }
  };
  return (
    <div>
      <Card
        title="评论列表"
        headerStyle={{ border: 'none', height: 'auto', paddingTop: '20px' }}
      >
        <div className={styles['search-form-wrapper']}>
          <Form
            form={form}
            className={styles['search-form']}
            labelAlign="left"
            labelCol={{ span: 5 }}
            wrapperCol={{ span: 19 }}
          >
            <Row gutter={24}>
              <Col span={colSpan}>
                <Form.Item label="名称" field="articleTitle">
                  <Input placeholder="请输入名称" allowClear />
                </Form.Item>
              </Col>
              <Col span={colSpan}>
                <Form.Item label="状态" field="auditStatus">
                  <Select
                    defaultValue={0}
                    placeholder="请选择审核状态"
                    style={{ width: 160, marginLeft: 20, marginRight: 20 }}
                    onChange={onSelectSearch}
                  >
                    {auditStatusOptions.map((option) => (
                      <Select.Option key={option.value} value={option.value}>
                        {option.label}
                      </Select.Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
            </Row>
          </Form>
          <div className={styles['right-button']}>
            <Space>
              <Button
                type="primary"
                icon={<IconSearch />}
                onClick={handleSearch}
              >
                查询
              </Button>
              <Button icon={<IconRefresh />} onClick={handleReset}>
                重置
              </Button>
            </Space>
          </div>
        </div>
        <div className={styles['button-group']}>
          <Space>
            <Button
              type="primary"
              icon={<IconThunderbolt />}
              onClick={() => {
                handleAudit({ _id: 0 });
              }}
            >
              一键审核
            </Button>
          </Space>
        </div>
        <Table
          rowKey="_id"
          loading={loading}
          onChange={onChangeTable}
          pagination={pagination}
          columns={columns}
          data={data}
          scroll={{ x: 1600 }}
        />
      </Card>
      <Modal
        title="审核"
        visible={visible}
        onOk={onOk}
        confirmLoading={confirmLoading}
        onCancel={onCancel}
      >
        <Form form={formMoal}>
          <Form.Item
            label="审核状态"
            field="auditStatus"
            rules={[{ required: true, message: '请选择审核状态' }]}
          >
            <Radio.Group>
              <Radio value={1}>通过</Radio>
              <Radio value={2}>驳回</Radio>
            </Radio.Group>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}

export default Comment;
